package com.dmz.czykt.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dmz.czykt.service.CzyktService;
import com.dmz.czykt.util.SocketClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

/**
 * @author lee
 */
@RestController
@Slf4j
public class CzyktController {

    @Autowired
    private CzyktService czyktService;
    @Value("${cspIp}")
    String cspIp;
    @Value("${cspPort}")
    String port;

    /**
     * YH008单笔银行账号验证接口 联机
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/bank/verfiyAccount")
    public String verfiyAccount(HttpServletRequest request) {
        String json = "";
        try {
            JSONObject param = getJsonParam(request);
            SocketClientUtil tc = new SocketClientUtil(cspIp, Integer.parseInt(port));
            String sendMsg = JSONUtil.toJsonStr(param);
            log.info("接收三方报文：{}", sendMsg);
            String length = SocketClientUtil.padding(sendMsg.getBytes(StandardCharsets.UTF_8).length + "", 7, "0", "L");
            String sendMsgSend = length + sendMsg;
            tc.send(sendMsgSend);
            json = tc.receive();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return json;
    }

    /**
     * YH010批量银行账号验证接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/bank/acceptValidatedDetail")
    public String acceptValidatedDetail(HttpServletRequest request) {
        try {
            JSONObject param;
            param = getJsonParam(request);
            JSONObject head = param.getJSONObject("head");
            String json = "{\"id\": \"YH010\",\"uuid\": \"" + head.getStr("uuid") + "\",\"callDate\": \"" + head.getStr("callDate") + "\",\"callTime\": \"" + head.getStr("callTime") + "\",\"callUser\": \"" + head.getStr("callUser") + "\",\"code\": \"200\",\"error\": \"\",\"areaCode\": \"" + head.getStr("areaCode") + "\",\"bankNo\": \"" + head.getStr("bankNo") + "\"}";
            JSONObject o1 = param.getJSONObject("data");
            String fileName = (String) o1.get("fileName");
            Runnable function = () -> {
                String funtionName = Thread.currentThread().getName();
                System.out.println("当前启动的线程：" + funtionName);
                try {
                    czyktService.acceptValidatedDetail(fileName, param);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            };
            new Thread(function).start();
            return json;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * YH005补贴明细接收接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/api/bank/acceptData")
    public String acceptData(HttpServletRequest request) {
        JSONObject param;
        try {
            param = getJsonParam(request);
            JSONObject head = param.getJSONObject("head");
            String json = "";

            JSONObject o1 = param.getJSONObject("data");
            String fileName = (String) o1.get("fileName");
            String re = czyktService.acceptData(fileName, param);
            String[] resarr = re.split("\\|");
            if (resarr[0].equals("200")) {
                json = "{\"id\": \"YH005\",\"uuid\": \"" + head.getStr("uuid") + "\",\"callDate\": \"" + head.getStr("callDate") + "\",\"callTime\": \"" + head.getStr("callTime") + "\",\"callUser\": \"" + head.getStr("callUser") + "\",\"code\": \"" + resarr[0] + "\",\"error\": \"\",\"areaCode\": \"" + head.getStr("areaCode") + "\",\"bankNo\": \"" + head.getStr("bankNo") + "\"}";
            } else {
                json = "{\"id\": \"YH005\",\"uuid\": \"" + head.getStr("uuid") + "\",\"callDate\": \"" + head.getStr("callDate") + "\",\"callTime\": \"" + head.getStr("callTime") + "\",\"callUser\": \"" + head.getStr("callUser") + "\",\"code\": \"" + resarr[0] + "\",\"error\": \"" + resarr[1] + "\",\"areaCode\": \"" + head.getStr("areaCode") + "\",\"bankNo\": \"" + head.getStr("bankNo") + "\"}";

            }
            System.out.println("返回三方报文:" + json);
            log.info("返回三方报文:{}", json);
            return json;
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
		return null;
    }

    // 定义允许的字符白名单正则表达式
    private static final Pattern SAFE_STRING_PATTERN = Pattern.compile("^[a-zA-Z0-9_\\-@\\.\\s]+$");

    private JSONObject getJsonParam(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                request.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        String rawJson = builder.toString();
        log.info("getJsonParam::原始报文buffer::{}", rawJson);

        // 对输入进行清理和验证
        JSONObject jsonObject = JSONUtil.parseObj(rawJson);
        return jsonObject;
    }


}
